﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Gagnatek.WebSite.Models;

namespace Gagnatek.WebSite.Controllers
{ 
    public class UsersController : Controller
    {
        private GagnatekDBEntities db = new GagnatekDBEntities();

        //
        // GET: /Users/
        [Authorize(Roles="Owner")]
        public ViewResult Index()
        {
            var users = db.Users.Include(u => u.Roles);
            return View(users.ToList());
        }

        //
        // GET: /Users/Details/5

        public ViewResult Details(int id)
        {
            Users users = db.Users.Find(id);
            return View(users);
        }

        //
        // GET: /Users/Create

        public ActionResult Create()
        {
            ViewBag.role_id = new SelectList(db.Roles, "id", "name");
            return View();
        } 

        //
        // POST: /Users/Create

        [HttpPost]
        public ActionResult Create(Users users)
        {
            if (ModelState.IsValid)
            {
                users.Roles = db.Roles.Where(r => r.name.Equals("Customer")).FirstOrDefault();
                db.Users.Add(users);
                db.SaveChanges();
                return RedirectToAction("Index");  
            }

            ViewBag.role_id = new SelectList(db.Roles, "id", "name", users.role_id);
            return View(users);
        }
        
        //
        // GET: /Users/Edit/5
 
        public ActionResult Edit(int id)
        {
            Users users = db.Users.Find(id);
            ViewBag.role_id = new SelectList(db.Roles, "id", "name", users.role_id);
            return View(users);
        }

        //
        // POST: /Users/Edit/5

        [HttpPost]
        public ActionResult Edit(Users users)
        {
            if (ModelState.IsValid)
            {
                db.Entry(users).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.role_id = new SelectList(db.Roles, "id", "name", users.role_id);
            return View(users);
        }

        //
        // GET: /Users/Delete/5
 
        public ActionResult Delete(int id)
        {
            Users users = db.Users.Find(id);
            return View(users);
        }

        //
        // POST: /Users/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {            
            Users users = db.Users.Find(id);
            db.Users.Remove(users);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}